#include <iostream>
#include <string>
#include <fstream>

#include "iniReader.h"

NT_IniReader::NT_IniReader(std::string f_Name)
{
	this->path = f_Name + ".ini";
}

std::string NT_IniReader::StringValue(std::string Section, std::string Key, std::string DefaultValue)
{
	std::fstream f;
	f.open(this->path.c_str(), std::ios::in);
	if(f.fail())
		return DefaultValue;

	std::string line, KeyValue, KeyTmp;
	std::string::size_type pLeft, pRight;
	bool sFound = false, kFound = false;

	while(getline(f,line))
	{
		if(!sFound && (line.size() <= 0 || line.size() != Section.size()+2))
			continue;
		if(sFound && !kFound && (line.size() <= 0 || line.size() < Key.size()+1))
			continue;
		if((pLeft = line.find_first_of("[=")) == std::string::npos)
			continue;

		switch(line[pLeft])
		{
		case '[':
			if((pRight = line.find_last_of("]")) != std::string::npos)
			{
				if(line.substr(1,line.size()-2) == Section)
					sFound = true;
			}
			break;
		case '=':
			KeyTmp = line.substr(0,pLeft);
			if(KeyTmp == Key)
			{
				KeyValue = line.substr(pLeft+1);
				kFound = true;
			}
			break;
		}

		if(sFound && kFound)
			break;
	}

	return !kFound ? DefaultValue : KeyValue;
}

int NT_IniReader::IntegerValue(std::string Section, std::string Key, int DefaultValue)
{
	std::fstream f;
	f.open(this->path.c_str(), std::ios::in);
	if(f.fail())
		return DefaultValue;

	int KeyValue;
	std::string line, KeyTmp;
	std::string::size_type pLeft, pRight;
	bool sFound = false, kFound = false;

	while(getline(f,line))
	{
		if(!sFound && (line.size() <= 0 || line.size() != Section.size()+2))
			continue;
		if(sFound && !kFound && (line.size() <= 0 || line.size() < Key.size()+1))
			continue;
		if((pLeft = line.find_first_of("[=")) == std::string::npos)
			continue;

		switch(line[pLeft])
		{
		case '[':
			if((pRight = line.find_last_of("]")) != std::string::npos)
			{
				if(line.substr(1,line.size()-2) == Section)
					sFound = true;
			}
			break;
		case '=':
			KeyTmp = line.substr(0,pLeft);
			if(KeyTmp == Key)
			{
				KeyValue = atoi(line.substr(pLeft+1).c_str());
				kFound = true;
			}
			break;
		}

		if(sFound && kFound)
			break;
	}

	return !kFound ? DefaultValue : KeyValue;
}